package cn.cutie.clot.fs;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.File;

/**
 * @Description:
 * @Author: Cutie
 * @CreateDate: 2024/7/23 15:02
 * @Version: 0.0.1
 */
@Component
public class MQSyncer {

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    private String topic = "clotfs";

    @Value("${clotfs.group}")
    private String group;

    @Value("${clotfs.path}")
    private String uploadPath;

    @Value("${clotfs.downloadUrl}")
    private String localDownloadUrl;

    /**
     * 采用从节点接收到消息，到主节点这边拉文件
     *
     * @param fileMeta
     */
    public void sync(FileMeta fileMeta) {
        Message<String> message = MessageBuilder.withPayload(JSON.toJSONString(fileMeta)).build();
        rocketMQTemplate.send(topic, message);
        System.out.println("===> send message: " + message);
    }

    @Service
    @RocketMQMessageListener(topic = "clotfs", consumerGroup = "${clotfs.group}")
//    public class FileMQSyncer implements RocketMQListener<String> {
    public class FileMQSyncer implements RocketMQListener<MessageExt> {

        @Override
        public void onMessage(MessageExt messageExt) {
            // 1. 从消息里面拿到meta数据
            System.out.println("===> receive message: " + messageExt + ", msgId: " + messageExt.getMsgId());
            String json = new String(messageExt.getBody());
            System.out.println("===> receive json: " + json);
            FileMeta fileMeta = JSON.parseObject(json, FileMeta.class);
            String downloadUrl = fileMeta.getDownloadUrl();
            if (downloadUrl == null || downloadUrl.isEmpty()) {
                System.out.println("===> downloadUrl is null or empty");
                return;
            }
            // 去重本机操作
            if (localDownloadUrl.equals(downloadUrl)){
                System.out.println("===> downloadUrl is localDownloadUrl, ignore download");
                return;
            }
            System.out.println("===> downloadUrl is not localDownloadUrl, start download");

            // 2. 写meta文件
            String dir = uploadPath + "/" + fileMeta.getName().substring(0, 2);
            File metaFile = new File(dir, fileMeta.getName() + ".meta");
            if (metaFile.exists()){
                System.out.println("===> meta file exists and ignore save: " + metaFile.getAbsolutePath());
            } else {
                System.out.println("===> meta file save: " + metaFile.getAbsolutePath());
                FileUtils.writeString(metaFile, json);
            }

            // 3. 下载文件
            File file = new File(dir, fileMeta.getName());
            if (file.exists() && file.length() == fileMeta.getSize()){
                System.out.println("===> file exists and ignore download: " + file.getAbsolutePath());
                return;
            }
            String download = downloadUrl + "?filename=" + file.getName();
            FileUtils.download(download, file);
        }
    }
}
